package com.wechat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP服务端
 */
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        try {
            // 1.创建连接
            serverSocket = new ServerSocket(9999);
            while (true) {
                // 2.监听用户消息 等待客户端发送消息过来
                accept = serverSocket.accept();
                // 3.接收读取用户消息
                is = accept.getInputStream();
                // 使用管道读取消息
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int len;
                // 循环读取
                while ((len = is.read(buf))!= -1) {
                    // 写入管道流 -- 转码
                    baos.write(buf,0,len);
                }
                // 输出读取内容
                System.out.println(baos.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 先开后关
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
